package com.ds.infrastructure.audit.collector.listener;

import com.alibaba.fastjson.JSON;
import com.ds.infrastructure.audit.collector.service.IMessageService;
import com.ds.infrastructure.audit.common.constant.CommonConstant;
import com.ds.infrastructure.audit.common.entity.KbaBehaviorWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/7/30
 */
@Slf4j
public class MessageListener {

    @Autowired
    private IMessageService messageService;

    @PostConstruct
    private void init() {
    }

    /**
     * Kafka
     *
     * @param records
     */
    @KafkaListener(topics = {CommonConstant.TOPIC_MSG_COLLECTOR})
    private void listen(List<ConsumerRecord<String, String>> records) {
        /*if (log.isDebugEnabled()) {
            log.debug("==Records Size={}", records.size());
        }*/
        if (CollectionUtils.isEmpty(records)) {
            return;
        }
        messageService.process(convert(records));
    }

    private List<KbaBehaviorWrapper> convert(List<ConsumerRecord<String, String>> recordList) {
        return recordList.stream().map(r -> {
            try {
                return JSON.parseObject(r.value(), KbaBehaviorWrapper.class);
            } catch (Exception e) {
                return new KbaBehaviorWrapper();
            }
        }).collect(Collectors.toList());
    }

}
